<template>
  <el-container class="app-container">
    <!-- 左侧菜单(item, index) in $router.options.routes.slice(1) -->
    <el-aside width="220px" class="aside">
      <el-menu
        router
        :default-active="$route.path"
        class="menu"
        background-color="#fff"
        text-color="#333333"
        active-text-color="#409EFF"
      >
        <!-- 子菜单（有 children 的） -->
        <el-sub-menu
          v-for="item in menuWithChildren"
          :index="'/' + item.url"
          :key="item.permissionId"
        >
          <template #title>
            <el-icon><icon-menu /></el-icon>
            <span>{{ item.permissionName }}</span>
          </template>

          <el-menu-item
            v-for="child in item.children"
            :index="'/' + child.url"
            :key="child.permissionId"
          >
            {{ child.permissionName }}
          </el-menu-item>
        </el-sub-menu>

        <!-- 顶级菜单（无 children 的） -->
        <el-menu-item
          v-for="item in menuWithoutChildren"
          :index="'/' + item.url"
          :key="item.permissionId"
        >
          {{ item.permissionName }}
        </el-menu-item>

      </el-menu>
    </el-aside>

    <!-- 主体 -->
    <el-container>
      <!-- 顶部栏 -->
      <el-header class="header">
        <div class="toolbar">

          <!-- 新增库存切换按钮 -->
          <div style="margin-left: 20px; display: inline-flex; align-items: center;">
            <span style="margin-right: 8px;">库存切换:</span>
            <el-cascader
              v-model="selectedStock"
              :options="storeList"
              clearable
              placeholder="请选择库存拥有者"
              style="width: 200px;"
              @change="confirmSwitch"
            />
          </div>
          <el-dropdown>
            <span class="user-menu">
              <el-icon style="font-size: 30px; "><setting /></el-icon>
              <span class="username-circle">{{ data.user.salerName }}</span>
            </span>

            <template #dropdown>

              <el-dropdown-item @click="forget">修改密码</el-dropdown-item>
              <el-dropdown-menu>
                <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

        </div>
      </el-header>

      <!-- 内容区 -->
      <el-main class="main-content">
        <RouterView />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
// 获取所有的菜单,在pinia中
// import { useMnuStore } from '@/store/menu'
import {reactive,onMounted,ref,computed } from 'vue'
import { RouterView, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Menu as IconMenu, Setting } from '@element-plus/icons-vue'
const router = useRouter()

const menuList = ref([])
const forget=()=>{
  router.push('/components/forget')
}

// 是否显示弹窗
const showStockDialog = ref(false)

// 级联选择绑定值
const selectedStock = ref('')

const companyMap = {
  '100': '湖南公司',
  '105': '湖南生物公司',
  '110': '湘西公司',
  '115': '怀化公司',
  '120': '益阳公司',
  '125': '岳阳公司',
  '130': '衡阳公司',
  '135': '邵阳公司',
};
const storeList = ref([])
const roleStr = localStorage.getItem('role') || ''
if (roleStr) {
  const roleArr = roleStr.split(',')
  storeList.value = roleArr.map(roleId => ({
    value: roleId,
    label: companyMap[roleId] || `未知角色(${roleId})`
  }))
}

  const confirmSwitch=()=>{
    if (!selectedStock.value) {
      ElMessage.error('请选择一个库存拥有者')
      return
    }
    localStorage.setItem('currentOwnerId', selectedStock.value)
    console.log('切换到角色:', selectedStock.value)
    showStockDialog.value = false
  }
onMounted(() => {
  const raw = localStorage.getItem('menuRoutes')
  if (raw) {
    menuList.value = JSON.parse(raw)
  }
})

const filterVisibleMenu=(menuList)=>{
  return menuList
    .filter(item => item.opFlag !== '1') // 不显示 opFlag 为 1 的菜单
    .map(item => {
      const newItem = { ...item }
      if (newItem.children && newItem.children.length > 0) {
        newItem.children = filterVisibleMenu(newItem.children)
      }
      return newItem
    })
}
const rawMenu = JSON.parse(localStorage.getItem('menuRoutes') || '[]')

// 先过滤掉不需要显示的菜单项
const visibleMenu = ref(filterVisibleMenu(rawMenu))

// 提取有子菜单的菜单项
const menuWithChildren = computed(() =>
  visibleMenu.value.filter(item => item.children && item.children.length > 0)
)

// 提取没有子菜单的菜单项（注意这里也用过滤后的 visibleMenu）
const menuWithoutChildren = computed(() =>
  visibleMenu.value.filter(item => !item.children || item.children.length === 0)
)


const data=reactive({
    user:JSON.parse(localStorage.getItem('code_user')||'{}')
})
// 判读是否有子菜单
// const hasChildren = (menu) => {
//   if(menu.children && menu.children.length > 0){
//     return true;
//   }
//   return false;
// }

// 切换路由
// const handleRouter=(menu)=>{
//   const hasNode = menuStore.tabList.filter(item => item.path == menu.path)
//   if(hasNode == null || hasNode.length == 0){
//     const data = {title: menu.menuName,path: menu.path}
//     menuStore.setTabList(data)
//   }
//   router.push(menu.path);
// }
const logout=()=>{
    localStorage.removeItem('code_user')
    localStorage.removeItem('menuRoutes')
    localStorage.removeItem('currentOwnerId')
    router.push('/login')
}
</script>

<style lang="scss" scoped>
.app-container {
  height: 100vh;
}

.aside {
  background-color: white;
  color: white;
  height: 100%;
  box-shadow: 2px 0 8px white;
}

.menu {
  border-right: none;
}

.header {
  background: #fff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 20px;
  height: 80px;
  box-shadow: 0 2px 8px white;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-menu {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: black;
  gap: 6px;
}

.username {
  font-weight: 500;
  font-size: 14px;
}

.main-content {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.username-circle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 100%;
  background-color: #4b76a1;
  color: white;
  font-weight: bold;
  font-size: 14px;
}


</style>
